using Microsoft.AspNetCore.Mvc;
using MusicLibrary.Server.Models;
using MusicLibrary.Server.Data;
using System.Linq;
using BCrypt.Net;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

[ApiController]
[Route("api/[controller]")]
public class AuthController : ControllerBase
{
    private readonly MusicLibraryContext _context;
    private readonly IConfiguration _config;
    public AuthController(MusicLibraryContext context, IConfiguration config)
    {
        _context = context;
        _config = config;
    }

    [HttpPost("login")]
    public IActionResult Login([FromBody] AuthRequest request)
    {
        try
        {
            if (!ModelState.IsValid)
                return BadRequest(ReturnMessage.Fail("请求无效"));

            var user = _context.Users.FirstOrDefault(u => u.UserName == request.UserName);
            if (user != null && BCrypt.Net.BCrypt.Verify(request.Password, user.PasswordHash))
            {
                var token = GenerateJwtToken(user);
                return Ok(ReturnMessage.Success(new { token, user }, "登录成功"));
            }
            return Ok(ReturnMessage.Fail("账号或密码错误"));
        }
        catch (Exception ex)
        {
            // 这里可以记录日志 ex
            return StatusCode(500, ReturnMessage.Fail("服务器内部错误: " + ex.Message));
        }
    }

    [HttpPost("register")]
    public IActionResult Register([FromBody] AuthRequest request)
    {
        if (!ModelState.IsValid)
            return BadRequest(ReturnMessage.Fail("请求无效"));

        if (_context.Users.Any(u => u.UserName == request.UserName))
            return Ok(ReturnMessage.Fail("用户名已存在"));

        if (!string.IsNullOrEmpty(request.Email) && _context.Users.Any(u => u.Email == request.Email))
            return Ok(ReturnMessage.Fail("邮箱已存在"));

        var passwordHash = BCrypt.Net.BCrypt.HashPassword(request.Password);

        var user = new User
        {
            UserName = request.UserName,
            Email = request.Email ?? "",
            PasswordHash = passwordHash,
            Role = "user",
            Avatar = "",
            Bio = "",
            Status = "active",
            CreatedAt = DateTime.Now
        };
        _context.Users.Add(user);
        _context.SaveChanges();

        var token = GenerateJwtToken(user);
        return Ok(ReturnMessage.Success(new { user, token }, "注册成功"));
    }

    private string GenerateJwtToken(User user)
    {
        var jwtConfig = _config.GetSection("Jwt");
        var claims = new[]
        {
            new Claim(JwtRegisteredClaimNames.Sub, user.UserName),
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
            new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
            new Claim(ClaimTypes.Role, user.Role)
        };

        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtConfig["Key"]));
        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

        var expires = DateTime.Now.AddMinutes(double.Parse(jwtConfig["ExpireMinutes"] ?? "120"));

        var token = new JwtSecurityToken(
            issuer: jwtConfig["Issuer"],
            audience: jwtConfig["Audience"],
            claims: claims,
            expires: expires,
            signingCredentials: creds
        );

        return new JwtSecurityTokenHandler().WriteToken(token);
    }
}